//===============================================================================
// Microsoft patterns & practices
// Mobile Client Software Factory - July 2006
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.Mobile.PasswordAuthentication;
using System.Security.Cryptography;
using System.IO;
using System.Xml;
using Microsoft.Practices.Mobile.Configuration;

namespace ConfigSectionEncrypt
{
	public class CryptoTasks
	{
		private const string containerName = "ConfigSectionEncrypt";

		public static byte[] DecryptKey(string username, string password, byte[] encryptedKey)
		{
			using (RsaAesCryptographyProvider provider = new RsaAesCryptographyProvider(containerName))
			{
				PasswordIdentity identity = new PasswordIdentity(username, password, provider);
				Rijndael algorithm = Rijndael.Create();
				CryptographyBlock block = new CryptographyBlock(algorithm, identity.CryptoKey);
				return block.Decrypt(encryptedKey);
			}
		}

		public static byte[] EncryptKey(string username, string password, byte[] key)
		{
			using (RsaAesCryptographyProvider provider = new RsaAesCryptographyProvider(containerName))
			{
				PasswordIdentity identity = new PasswordIdentity(username, password, provider);
				Rijndael algorithm = Rijndael.Create();
				CryptographyBlock block = new CryptographyBlock(algorithm, identity.CryptoKey);
				return block.Encrypt(key, algorithm.IV);
			}
		}

		public static byte[] GenerateKey()
		{
			SymmetricAlgorithm algorithm = Rijndael.Create();
			return algorithm.Key;
		}

		public static string EncryptSection(string section, byte[] key)
		{
			//
			// First, we need to get the name of the root element for the section, which we'll put
			// into the name attribute of the <EncryptedSection> element.
			//
			StringReader reader = new StringReader(section);
			XmlTextReader xml = new XmlTextReader(reader);

			while (!xml.EOF && xml.NodeType != XmlNodeType.Element)
				xml.Read();

			string sectionName = xml.Name;

			xml.Close();
			reader.Close();

			using (RsaAesCryptographyProvider provider = new RsaAesCryptographyProvider("ConfigSectionEncrypt"))
			{
				byte[] data = EncryptSectionData(section, key);
				string encryptedSection = @"<EncryptedSection name=""{0}"">{1}</EncryptedSection>";
				encryptedSection = String.Format(encryptedSection, sectionName, Convert.ToBase64String(data));

				return encryptedSection;
			}
		}

		private static byte[] EncryptSectionData(string section, byte[] key)
		{
			Rijndael crypt = Rijndael.Create();
			CryptographyBlock block = new CryptographyBlock(crypt, key);
			return block.Encrypt(CryptographyUtility.GetBytes(section), crypt.IV);
		}

		public static string DecryptSection(string encryptedSection, byte[] key)
		{
			StringReader reader = new StringReader(encryptedSection);
			XmlReader xml = XmlTextReader.Create(reader);

			while (!xml.EOF && xml.NodeType != XmlNodeType.Element)
				xml.Read();

			if (xml.Name != "EncryptedSection")
				throw new ArgumentException("section");

			string encryptedXml = xml.ReadInnerXml();
			xml.Close();
			reader.Close();

			Rijndael crypt = Rijndael.Create();
			CryptographyBlock block = new CryptographyBlock(crypt, key);
			byte[] data = block.Decrypt(Convert.FromBase64String(encryptedXml));
			return CryptographyUtility.GetString(data);
		}
	}
}
